package com.ym.ms.controller;

import com.cdk8s.tkey.client.rest.TkeyProperties;
import com.cdk8s.tkey.client.rest.pojo.bo.OAuth2AccessToken;
import com.cdk8s.tkey.client.rest.pojo.dto.OauthUserProfile;
import com.cdk8s.tkey.client.rest.pojo.dto.TkeyToken;
import com.cdk8s.tkey.client.rest.service.TkeyService;
import com.cdk8s.tkey.client.rest.utils.CodecUtil;
import com.ym.ms.commons.AuthVariable;
import com.ym.ms.utils.CookieUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * @author zetor
 */
@Slf4j
@Controller
public class AuthController {

    @Autowired
    private TkeyService tkeyService;

    @Autowired
    private TkeyProperties tkeyProperties;

    @Value("${front_url}")
    private String front_url;

    //=====================================业务处理 start=====================================

    /**
     * 接收 code，然后换取 token
     */
    @SneakyThrows
    @RequestMapping(value = "/codeCallback", method = RequestMethod.GET)
    public void codeCallback(final HttpServletRequest request, final HttpServletResponse response, @RequestParam(value = "redirect_uri", required = true) String redirectUri) {
        String code = request.getParameter("code");

        if (StringUtils.isBlank(code)) {
            return;
        }

        getAccessToken(request, response, code);
        // 重定向到原请求地址
        redirectUri = CodecUtil.decodeURL(redirectUri);
		response.sendRedirect(redirectUri);
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(final HttpServletRequest request, final HttpServletResponse response) {
        String finalLogoutUri = tkeyProperties.getFinalLogoutUri();
        CookieUtil.remove(request, response, AuthVariable.SSO_SESSIONID);
        return "redirect:" + finalLogoutUri;
    }


    private TkeyToken getAccessToken(HttpServletRequest request, HttpServletResponse response, String code) {
        OAuth2AccessToken oauthToken = tkeyService.getAccessToken(code);
        String accessToken = oauthToken.getAccessToken();

        TkeyToken tkeyToken = new TkeyToken();
        tkeyToken.setAccessToken(accessToken);
        tkeyToken.setRefreshToken(oauthToken.getRefreshToken());
        OauthUserProfile user = tkeyService.getUserProfile(oauthToken);
        tkeyToken.setAttributes(user);

        CookieUtil.set(response, AuthVariable.SSO_SESSIONID, accessToken, false);
        return tkeyToken;
    }


    @RequestMapping(value = "/logoutSuccess", method = RequestMethod.GET)
    @ResponseBody
    private String logoutSuccess() {
        return "登出成功";
    }

    @RequestMapping(value = "/auth/user")
    @ResponseBody
    private Map user(@RequestHeader(value = "x-token") String accessToken) {
        OAuth2AccessToken oauthToken = new OAuth2AccessToken();
        oauthToken.setAccessToken(accessToken);
        OauthUserProfile user = tkeyService.getUserProfile(oauthToken);

        Map<String, Object> map = new HashMap<>();
        map.put("userinfo", user);
        return map;
    }

    //=====================================私有方法  end=====================================
}
